var TXT_NETBUSY = "\u7f51\u7edc\u7e41\u5fd9\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5\u2026";
var TXT_NETWAIT = "\u6b63\u5728\u83b7\u53d6\u6570\u636e\uff0c\u8bf7\u7a0d\u5019\u2026";
var TXT_POSTDATA = "\u6b63\u5728\u63d0\u4ea4\u6570\u636e\uff0c\u8bf7\u7a0d\u5019\u2026";
var _SEARCH_CANCEL = false;
var _SEARCH_TYPE = '';
var _SEARCH_COUNT = 0;
var _SEARCH_UNIT = 2;
var _SITE_PEANUT = 'localhost' // 'www.oray.cn';
var _SITE_DOMAIN = 'localhost' // 'domain.oray.cn';
var _SITE_STATIC = 'localhost' // 'static.oray.net';
String.prototype.toInt = function() {
	return $.func.checkInt(this)
};
function moveOption(from, to) {
	from = $(from)[0];
	to = $(to)[0];
	for ( var i = from.options.length - 1; i >= 0; i--) {
		if (from.options[i].selected && from.options[i].value != '') {
			to.options.add(new Option(from.options[i].text,
					from.options[i].value));
			from.options[i] = null
		}
	}
}
function checkboxAll(name, o) {
	if (o.type != "checkbox")
		return false;
	if (o.type != 'checkbox')
		o.checked = o.checked === null ? true : !o.checked;
	$("input[name='" + name + "']:checkbox:enabled").attr("checked", o.checked)
}
function checkboxVal(name) {
	var val = [];
	$("input:checkbox[name=" + name + "]:enabled:checked").each( function() {
		val.push(this.value)
	});
	return val
}
function getData(o) {
	return eval("false||" + $(o).attr('data'))
}
function setTag(o) {
	var tags = $("#tags").val().split(" ");
	var ret = [], done = {};
	var add = !$(o).hasClass("orange");
	var tag = $(o).html();
	if (add)
		tags.push(tag);
	else
		tags = $.grep(tags, function(i) {
			return i != tag
		});
	$.each(tags, function() {
		if (!done[this] && this != "") {
			done[this] = true;
			ret.push(this)
		}
	});
	$("#tags").val(ret.join(" "));
	$(o).toggleClass("orange")
}
function checkDomain(domains, fn, free) {
	if (!domains.length)
		return;
	if (domains.constructor != Array)
		domains = [ domains ];
	var _domains = [];
	for ( var i = 0; (i < _SEARCH_UNIT && domains.length > 0); i++) {
		_domains.push(domains.shift())
	}
	$.ajax( {
		type :"POST",
		url :"/domain/check.php",
		data : {
			domain :_domains.join(','),
			free :free ? "1" : "0"
		},
		dataType :"json",
		success : function(ret) {
			fn(ret, domains.length, free);
			if (domains.length && !_SEARCH_CANCEL) {
				checkDomain(domains, fn, free)
			}
		},
		error : function(res) {
			fn(_domains, domains.length, free);
			if (domains.length && !_SEARCH_CANCEL) {
				checkDomain(domains, fn, free)
			}
		}
	})
}
function checkStatus(o) {
	var status = o.className;
	var domain = o.name;
	if (status == "disable" || status == "expire") {
		window.open("http://" + _SITE_DOMAIN + "/whois/?domain="
				+ encodeURIComponent(domain), "whois")
	} else if (status == "enable") {
		if (location.hostname == _SITE_DOMAIN) {
			addPending(domain, true)
		} else {
			window.open("http://" + _SITE_PEANUT
					+ "/payment/domain_reg.php?domain="
					+ encodeURIComponent(domain), "domainreg")
		}
	} else if (status == "loading") {
		alert(TXT_POSTDATA)
	} else {
		if (_SEARCH_COUNT < 0)
			_SEARCH_COUNT = 0;
		if (_SEARCH_COUNT >= 5)
			return alert(TXT_POSTDATA);
		$("a[name=" + domain + "]").attr("class", "loading");
		checkDomain(domain, updateStatus);
		_SEARCH_COUNT++
	}
}
function updateStatus(rets, time) {
	var status = "timeout";
	if (typeof rets == "string") {
		$("a[name=" + rets + "]").attr("class", status);
		return
	}
	$(rets).each( function() {
		var domain = this.domain ? this.domain : this;
		if (this.ret == 100) {
			status = "enable"
		} else if (this.ret == 0) {
			status = "disable"
		}
		$("a[name=" + domain + "]").attr("class", status);
		_SEARCH_COUNT--
	})
}
function toRegister(domain, free) {
	if (!domain)
		domain = checkboxVal("domain");
	if (domain.constructor != Array)
		domain = [ domain ];
	if (!domain.length)
		return alert("\u8bf7\u9009\u62e9\u8981\u6ce8\u518c\u7684\u57df\u540d");
	if (free)
		var url = "http://" + _SITE_PEANUT + "/payment/domain_free.php?domain="
				+ encodeURIComponent(domain.join(","));
	else
		var url = "http://" + _SITE_PEANUT + "/payment/domain_reg.php?domain="
				+ encodeURIComponent(domain.join(","));
	window.open(url)
}
function initSearch() {
	$("#dmContainer .dmIcon .stop").click(cancelSearch);
	$("#dmContainer .dmBottom button[name=reg]").click( function() {
		var domains = [];
		$("#dmResult :checked").each( function() {
			domains.push(this.value)
		});
		toRegister(domains, (_SEARCH_TYPE == "free"))
	});
	$("#dmContainer .dmBottom button[name=retry]").click(searchTimeoutDomain);
	$("#dmContainer .dmBottom button[name=collect]").click( function() {
		$("#prefixform").submit()
	})
}
function searchDomain(prefixes, suffixes, type) {
	var isfree = (type == 'free');
	var domains = [];
	var kumi = false;
	if (!suffixes)
		suffixes = '';
	if (typeof prefixes == 'string') {
		prefixes = [ prefixes ];
		kumi = true
	}
	;
	if (typeof suffixes == 'string')
		suffixes = [ suffixes ];
	$(prefixes).each( function() {
		var prefix = this;
		$(suffixes).each( function() {
			var suffix = this;
			domains.push(prefix + suffix)
		})
	});
	_SEARCH_CANCEL = false;
	_SEARCH_TYPE = type;
	$.modal.close();
	$("#dmContainer .loading,#dmContainer .stop").show();
	$("#dmContainer .dmBottom button,#dmPrefix").hide();
	$("#dmResult").html("");
	$("#dmContainer")
			.modal(
					{
						close :false,
						onShow : function() {
							if (!isfree && kumi) {
								$
										.ajax( {
											type :"POST",
											url :"/domain/prefix.php",
											data : {
												name :prefixes[0]
											},
											dataType :"html",
											success : function(ret) {
												if (!ret)
													$("#dmPrefix").html("")
															.hide();
												else {
													$("#dmPrefix").html(ret)
															.show();
													$(
															"#dmContainer button[name=collect]")
															.show();
													var validator = validatePrefix(
															"#prefixform",
															function() {
																$("#dmPrefix")
																		.html(
																				"")
																		.hide();
																$(
																		"#dmContainer button[name=collect]")
																		.hide()
															})
												}
											},
											error : function(res) {
												$("#dmPrefix").hide()
											}
										})
							}
							checkDomain(domains, updateResult, isfree)
						},
						onClose : function() {
							cancelSearch();
							$.modal.close()
						}
					})
}
function searchTimeoutDomain() {
	var domains = [];
	$("#dmResult span[_status=50]").each( function(i) {
		domains.push($(this).attr("_value"));
		$(this).remove()
	});
	$("#dmContainer .loading,#dmContainer .stop").show();
	$("#dmContainer .dmBottom button,#dmPrefix").hide();
	checkDomain(domains, updateResult, (_SEARCH_TYPE == 'free'))
}
function updateResult(rets, time, free) {
	if (typeof rets == "string")
		rets = rets.split(",");
	var img = 'http://' + _SITE_STATIC + '/default/images/';
	var strEnabled = '<input id="$root$" type="checkbox" value="$root$" onclick="pendingReg(\'$domain$\',this)" /><img src="$img$icon_enabled.gif" />$root$';
	var strDisabled = '<img src="$img$icon_disabled.gif" /><a href="http://' + _SITE_DOMAIN + '/whois/?domain=$domain$" target="_blank">$root$</a>';
	var strTimeOut = '<img src="$img$icon_timeout.gif" />$root$';
	var strFreeDisabled = '<img src="$img$icon_disabled.gif" />$root$';
	var strFreeEnabled = '<input id="$root$" type="radio" name="radiobutton" value="$root$" /><img src="$img$icon_enabled.gif" />$root$';
	if (free) {
		strEnabled = strFreeEnabled;
		strDisabled = strFreeDisabled
	}
	var status = 50, domain = "";
	var str = "", html = "";
	$
			.each(
					rets,
					function() {
						domain = (typeof this.domain == "string") ? this.domain
								: this;
						status = (typeof this.ret == "number") ? this.ret : 50;
						if (status == 100) {
							str = strEnabled
						} else if (status == 0) {
							str = strDisabled
						} else {
							status = 50;
							str = strTimeOut
						}
						str = '<span _status="$status$" _value="$root$"><label for="$root$">' + str + '</label>&nbsp;</span>';
						str = str.replace(/\$img\$/g, img);
						str = str.replace(/\$status\$/g, status);
						str = str.replace(/\$root\$/g, domain);
						str = str.replace(/\$domain\$/g, encodeURI(domain));
						html += str
					});
	$("#dmResult").append(html);
	if (!time)
		finishSearch()
}
function cancelSearch() {
	_SEARCH_CANCEL = true;
	finishSearch(true)
}
function finishSearch(b) {
	if (_SEARCH_CANCEL & !b)
		return;
	$("#dmContainer .loading,#dmContainer .stop").hide();
	if ($("#dmResult span[_status=100]").size() > 0) {
		$("#dmContainer .dmBottom button[name=reg]").show()
	}
	if ($("#dmResult span[_status=50]").size() > 0) {
		$("#dmContainer .dmBottom button[name=retry]").show()
	}
}
function pendingReg(domain, o) {
	if ($(o).attr('done'))
		return;
	$(o).attr('done', true);
	if (location.hostname == _SITE_DOMAIN) {
		addPending(domain, true);
		return
	}
	$.ajax( {
		type :"POST",
		url :'/domain/domain.php',
		data : {
			act :'pending',
			domain :domain
		},
		dataType :"json",
		success : function(ret) {
		},
		error : function(res) {
		}
	})
}
function savePrefix(form, fn) {
	if (!form)
		return false;
	var data = $(form).serializeArray();
	$(form).disabled();
	$.ajax( {
		type :"POST",
		url :$(form).attr("action"),
		data :data,
		dataType :"json",
		success : function(ret) {
			alert(ret.msg);
			if (ret.success) {
				if (fn)
					fn();
				else
					window.location = "../home/"
			} else {
				$(form).enabled()
			}
		},
		error : function(res) {
			alert(TXT_NETBUSY);
			$(form).enabled()
		}
	})
}
function validatePrefix(form, fn) {
	var validator = $(form).validate( {
		onkeyup : function() {
		},
		onblur : function() {
		},
		onclick : function() {
		},
		errorClass :'_error',
		showErrors : function(errors, errorList) {
			var error = this.errorList[0];
			if (error) {
				error.element.focus();
				alert(error.message);
				return
			}
		},
		submitHandler : function(form) {
			savePrefix(form, fn)
		},
		rules : {
			name : {
				required :true
			},
			classid : {
				required :true,
				minValue :0
			},
			memo : {
				required :true,
				rangeLength : [ 3, 200 ]
			},
			tags : {
				required :true
			}
		},
		messages : {
			name :"\u8bf7\u8f93\u5165\u9177\u7c73\u540d\u79f0",
			classid :"\u8bf7\u9009\u62e9\u8d77\u540d\u7c7b\u578b",
			tags : {
				required :"\u8bf7\u8f93\u5165\u9177\u7c73\u6807\u7b7e"
			},
			memo : {
				required :"\u8bf7\u8f93\u5165\u6982\u8981\u8bf4\u660e",
				rangeLength :String.format("\u6982\u8981\u8bf4\u660e\u957f\u5ea6{0}-{1}\u4e4b\u95f4")
			}
		}
	});
	return validator
}